package com.zhiqianbao.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.FronBackpiction;
import com.zhiqianbao.entity.User;
import com.zhiqianbao.entity.UserIdphoto;
import com.zhiqianbao.entity.UserInfo;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.SystemUtils;
import com.zhiqianbao.utils.TimeStatisticsUtil;
import com.zhiqianbao.view.ProcessProgressBarView;
import com.zx.android.api.APICallback;
import com.zx.android.api.ConfigureObject;
import com.zx.android.api.ResultCode;
import com.zx.android.api.ZXApi;
import com.zx.android.api.data.IDCard;
import com.zx.android.api.data.Member;
import com.zx.android.api.data.MemberDetail;
import java.util.HashMap;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;
/**
 * Created by liang on 2016/3/3.
 */
public class FirstTimeConfirmInfoProgressThreeZx extends BaseActivity implements View.OnClickListener {
    public static final int DATA_FAILED=0x123;
    public static final int DATA_SCUESSFUL=0x124;
    private Gson gson = new Gson();
    private final String TAG = FirstTimeConfirmInfoProgressThreeZx.class.getSimpleName();
    private static final int HANDLER_MESSAGE = 1015;
    /**
     * 开始认证按钮
     */
    Button startButton;
    private TextView topbar_textview_title;
    private Button button_return;
    SharedPreferanceUtils sharedPreferanceUtils;
    private ProcessProgressBarView processView;
    ZXApi api;
    private String startTimes="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirmation);
        init();
        initView();
    }


    private void initView() {
        Button startButton=(Button)findViewById(R.id.start_button);
        initApi();
        startButton.setOnClickListener(this);
        topbar_textview_title = (TextView) findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("首次信息确认");
        button_return = (Button) findViewById(R.id.button_return);
        button_return.setOnClickListener(this);
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        processView= (ProcessProgressBarView) findViewById(R.id.process_layout);
        //芝麻开启状态,1开启，0未开启
        String zhimaOpenOrClose = sharedPreferanceUtils.getZhimaOpenOrClose();
        if("1".equals(zhimaOpenOrClose)){
            processView.openZhiMaProcess(ProcessProgressBarView.IS_SHOW_ZHIMA,1);
        }
        else{
            processView.openZhiMaProcess(ProcessProgressBarView.NOTIS_SHOW_ZHIMA,1);
        }
    }

    private void initApi() {
        api = ZXApi.getInstance();
        ConfigureObject configureObject = new ConfigureObject();
        if ("1".equals(Constants.TEXTORTRUE)) {
            //真信
            configureObject.setAppId(Constants.CLIENT_APP_ID);
            configureObject.setAppSecret(Constants.CLIENT_APP_SECRET);
        } else {
            //        //这是测试的
            configureObject.setAppId(Constants.CLIENT_APP_ID_TEXT);
            configureObject.setAppSecret(Constants.CLIENT_APP_SECRET_TEXT);
        }

        boolean b = api.configure(this, configureObject);
        if (!b) {
            showShortToast1("初始化失败，请联系客服！");
        }
    }

    @Override
    public void onClick(View v) {
        if(R.id.start_button==v.getId()) {
                Map<String, String> systemInfo = SystemUtils.getSystemInfo(FirstTimeConfirmInfoProgressThreeZx.this);
                if (systemInfo != null) {
                    String imei = systemInfo.get("imei");
                    if (TextUtils.isEmpty(imei)) {
                        imeiJugeMsg();
                        return;
                    }
                }

                if (api != null) {
                    //统计身份证开始验证时间
                    startTimes=TimeStatisticsUtil.getTime();
                    try {
                        String uid = "" + Constants.LOGIN_USER.getId();
                        String phone = Constants.LOGIN_USER.getPhone();
                        api.bind(uid, phone, new APICallback() {
                            @Override
                            public void bind_Callback(int code, String message, MemberDetail memberDetailOut) {
                                Log.i(getClass().getSimpleName(), code + "");
                                outputMemberDetail(code, message, memberDetailOut);
                                closeWaitDialog();
                            }
                        });
                    } catch (Exception e) {

                    }
                }
        }
        else if(R.id.button_return==v.getId()){
                finish();
        }
    }

    private void outputMemberDetail(int code, String message, MemberDetail memberDetail) {
        Log.i(TAG, "code:" + code);
        switch (code) {
            case ResultCode.USER_CANCELED:
                closeWaitDialog();
                return;
//            case ResultCode.USERID_ALREADY_EXIST:
//               /* api.unbind(Constants.LOGIN_USER.getId() + "", "99", "其他原因",new APICallback() {
//                    @Override
//                    public void unbind_Callback(int code, String message) {
//                        Log.i(TAG, "解绑返回的code: " + code);
//                        Log.i(TAG, "解绑返回的message: " + message);
//                        //解绑成功 或者 uid 不存在 可以进行重新认证
//                        if (ResultCode.INVALID_USER == code || ResultCode.SUCCESSED == code) {
//                            api.bind(Constants.LOGIN_USER.getId() + "", Constants.LOGIN_USER.getPhone(), new APICallback() {
//                                @Override
//                                public void bind_Callback(int code, String message, MemberDetail memberDetailOut) {
//                                    Log.i(getClass().getSimpleName(), code + "");
//                                    outputMemberDetail(code, message, memberDetailOut);
//                                }
//                            });
//                        }
//                    }
//                });*/
//                //如果已经绑定，直接获取绑定信息即可
//                api.getMemberDetail(Constants.LOGIN_USER.getId() + "", new APICallback() {
//                    @Override
//                    public void getMemberDetail_Callback(int code, String message, MemberDetail memberDetailOut) {
//                        //如果id不存在
//                        if (ResultCode.INVALID_USER == code) {
//                            api.bind(Constants.LOGIN_USER.getId() + "", Constants.LOGIN_USER.getPhone(), new APICallback() {
//                                @Override
//                                public void bind_Callback(int code, String message, MemberDetail memberDetailOut) {
//                                    Log.i(getClass().getSimpleName(), code + "");
//                                    outputMemberDetail(code, message, memberDetailOut);
//                                }
//                            });
//                        } else if (ResultCode.SUCCESSED == code) {
//                            outputMemberDetail(code, message, memberDetailOut);
//                        }
//                    }
//                });
//                break;
            case ResultCode.INVALID_USER:
                //解绑
                api.unbind(Constants.LOGIN_USER.getId() + "", "99", "其他原因", new APICallback() {
                    @Override
                    public void unbind_Callback(int code, String message) {
                        Log.i("解绑了....", "个人身份无效解绑返回的code: " + code);
                        Log.i("解绑了....", "个人身份无效解绑返回的message: " + message);
                        //解绑成功 或者 uid 不存在 可以进行重新认证
                        if (ResultCode.INVALID_USER == code || ResultCode.SUCCESSED == code) {
                            api.bind(Constants.LOGIN_USER.getId() + "", Constants.LOGIN_USER.getPhone(), new APICallback() {
                                @Override
                                public void bind_Callback(int code, String message, MemberDetail memberDetailOut) {
                                    Log.i(getClass().getSimpleName(), code + "");
                                    outputMemberDetail(code, message, memberDetailOut);
                                    closeWaitDialog();
                                }
                            });
                        }
                    }
                });

            case ResultCode.NETWORK_ERROR:
                showShortToast1("请稍后再试");
                break;
            case ResultCode.INTERNEL_ERROR:
                showShortToast1("请稍后再试");
                break;
            case ResultCode.SUCCESSED:
                thressSaveUserInfo(memberDetail);
                break;
        }
    }

    public void thressSaveUserInfo(MemberDetail memberDetail){
        if (memberDetail == null) {
           return;
        }
        Member member = memberDetail.getMember();

        float faceCertConfidence = member.faceCertConfidence;
        Log.i(TAG, "身份匹配度：" + faceCertConfidence);

        final IDCard idcard = memberDetail.getIdcard();


        final String idcardNum = member.idcard;
        String sex = getSexByIdcard(member.idcard);
        final String name = member.memberName;
        String mobileNo = member.mobileNo;

        sharedPreferanceUtils.setPhone(mobileNo);
        sharedPreferanceUtils.setidCard(idcardNum);
        sharedPreferanceUtils.setName(name);
        //身份证正面照片
        final String urlFront = idcard.front.imgUrl;
        //身份证地址
        final String address = idcard.front.address;
        //身份证背面照片
        final String urlFack = idcard.back.imgUrl;
        // 获得用户提交的身份证头像地址
        String urlFaceUser = idcard.front.imgFaceUrl;
        // 获得公安部的身份证头像地址
        final String urlFaceOfficial = idcard.front.imgOfficialFaceUrl;
        String realPhoto = "";
        if (member.imgUrls != null && member.imgUrls.length > 0) {
            realPhoto = member.imgUrls[member.imgUrls.length - 1];
        }
        final String realPhoto2 = realPhoto;

        //添加时间统计
        final String endTime = TimeStatisticsUtil.getTime();
        showWaitDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                mapParams.put("idcardHand", realPhoto2);
                mapParams.put("idcardBack", urlFack);
                mapParams.put("idcardFront", urlFront);
                mapParams.put("mobileIdCardHand", realPhoto2);
                mapParams.put("mobileIdCardBack", urlFack);
                mapParams.put("mobileIdCardFront", urlFront);
                mapParams.put("name", name);
                mapParams.put("idcard", idcardNum);
                mapParams.put("idcardPhoto", urlFaceOfficial);
                mapParams.put("address", address);
                mapParams.put("startTime", startTimes);
                mapParams.put("endTime", endTime);
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/thirdSaveUserInfoSecond",
                        mapParams, FirstTimeConfirmInfoProgressThreeZx.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILED;
                } else {
                    message.what = DATA_SCUESSFUL;
                    FronBackpiction data =gson.fromJson(result, FronBackpiction.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FAILED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case DATA_SCUESSFUL:
                    FronBackpiction response= (FronBackpiction) msg.obj;
                    closeWaitDialog();
                    if (response == null) {
                        showShortToast1("连接超时！");
                    } else {
                        //请求成功
                        if (Constants.DEFAULT_SUCCESS_CODE.equals(response.getCode())) {
//                                            User loginUser = gson.fromJson(gson.toJson(response.getData().get("user")), User.class);
                            User loginUser = response.getData().getUser();
                            UserIdphoto idPhoto = response.getData().getIdPhoto();
                            UserInfo userInfo = response.getData().getUserInfo();
//                                            UserIdphoto idPhoto = gson.fromJson(gson.toJson(result.getData().get("idPhoto")), UserIdphoto.class);
//                                            UserInfo userInfo = gson.fromJson(gson.toJson(result.getData().get("userInfo")), UserInfo.class);
                            Constants.LOGIN_USER = loginUser;
                            userInfo.save();
                            loginUser.save();
                            UserIdphoto.deleteAll(UserIdphoto.class);
                            idPhoto.save();
                            try {
                                String telecon = SharedPreferanceUtils.getTelecon();//运营商
                                String taoBao = SharedPreferanceUtils.getTaoBao();
                                String emergency = SharedPreferanceUtils.getEmergency();//紧急联系人
                                String job = SharedPreferanceUtils.getJobState();//工作
                                String zhima_state = SharedPreferanceUtils.getZhiMaState();//芝麻信用

                                if (telecon.equals("1")) {
                                    if (zhima_state.equals("1") || zhima_state.equals("2")) {
                                        if (emergency.equals("1") || emergency.equals("2")) {
                                            if (job.equals("1") || job.equals("2")) {
                                                startActivity(new Intent(FirstTimeConfirmInfoProgressThreeZx.this, CertificationSdActivity.class));
                                                FirstTimeConfirmInfoProgressThreeZx.this.finish();
                                            } else {
                                                startActivity(new Intent(FirstTimeConfirmInfoProgressThreeZx.this, FourthActivity.class));
                                                FirstTimeConfirmInfoProgressThreeZx.this.finish();
                                            }
                                        } else {
                                            startActivity(new Intent(FirstTimeConfirmInfoProgressThreeZx.this, ThirdActivity.class));
                                            FirstTimeConfirmInfoProgressThreeZx.this.finish();
                                        }
                                    } else {
                                        startActivity(new Intent(FirstTimeConfirmInfoProgressThreeZx.this, ZhiMaActivity.class));
                                        FirstTimeConfirmInfoProgressThreeZx.this.finish();
                                    }

                                } else {
                                    startActivity(new Intent(FirstTimeConfirmInfoProgressThreeZx.this, BindPhoneConfirmActivity.class));
                                    FirstTimeConfirmInfoProgressThreeZx.this.finish();
                                }
                            } catch (Exception e) {

                            }
                            api.destroy();
                        } else {
                            try {
                                api.unbind(Constants.LOGIN_USER.getId() + "", "99", "其他原因", new APICallback() {
                                    @Override
                                    public void unbind_Callback(int code, String message) {
                                        Log.i("解绑了....", "保存失败后解绑返回的code: " + code);
                                        Log.i("解绑了....", "解绑返回的message: " + message);
                                        //解绑成功 或者 uid 不存在 可以进行重新认证
                                        if (ResultCode.INVALID_USER == code || ResultCode.SUCCESSED == code) {
                                            api.bind(Constants.LOGIN_USER.getId() + "", Constants.LOGIN_USER.getPhone(), new APICallback() {
                                                @Override
                                                public void bind_Callback(int code, String message, MemberDetail memberDetailOut) {
                                                    Log.i(getClass().getSimpleName(), code + "");
                                                    outputMemberDetail(code, message, memberDetailOut);
                                                }
                                            });
                                        }
                                    }
                                });
                            } catch (Exception e) {

                            }

                            showShortToast1(response.getMsg());
                        }
                    }
                    break;
            }
        }
    };
    private String getSexByIdcard(String idcard) {
        String sex = null;
        if (!StringUtils.isBlank(idcard) && idcard.length() >= 15) {
            int len = idcard.length();
            if (len == 15) {
                try {
                    sex = Integer.parseInt(idcard.substring(14, 15)) % 2 == 0 ? "0"
                            : "1";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    sex = Integer.parseInt(idcard.substring(16, 17)) % 2 == 0 ? "0"
                            : "1";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return sex;
    }

    public void imeiJugeMsg(){
        final AlertDialog builder = new AlertDialog.Builder(this,R.style.Dialog).create();
        builder.show();
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_login_other_layout, null);
        builder.getWindow().setContentView(view);
        builder.setCanceledOnTouchOutside(false);
        Button button=(Button)view.findViewById(R.id.positiveButton);
        TextView msgTv=(TextView)view.findViewById(R.id.message);
        TextView titleTv = (TextView) view.findViewById(R.id.title);
        titleTv.setText("提示");
        msgTv.setText("您尚未开启手机设备串号读取权限，请开启相关权限！");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
    }
}
